{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 张量的拼接\n",
    "x = torch.Tensor([[1,2,3,4],[5,6,7,8],[9,0,1,2]])\n",
    "y = torch.zeros((3,4))\n",
    "torch.cat((x,y),dim=0) # 在第一维拼接\n",
    "torch.cat((x,y),dim=1) # 在第二维拼接"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 广播机制，对于形状不同的张量，自动复制来匹配运算\n",
    "a = torch.tensor([[[1],[2],[3]]])\n",
    "b = torch.tensor([1,1,1])\n",
    "print(a.shape,b.shape)\n",
    "print(a+b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 节省内存，原地赋值\n",
    "a = torch.tensor([[1,2,3],[1,2,3]])\n",
    "b = torch.tensor([1,2,3])\n",
    "before = id(a)\n",
    "# a = a + b  # ×\n",
    "# a += b  # √\n",
    "a[:] = a + b  # √\n",
    "print(id(a)==before)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 张量的赋值\n",
    "a = torch.Tensor([1,2,3,4])\n",
    "b = a\n",
    "id(a) == id(b) # Teue\n",
    "b = a.clone()\n",
    "id(a) == id(b) # False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 矩阵求和;均值同理mean()\n",
    "a = torch.ones((2,3,4))\n",
    "a\n",
    "a,a.sum(dim=0),a.sum(dim=1),a.sum(dim=2) # 若不想降维，可选参数keepdims"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 乘积\n",
    "torch.dot()\n",
    "torch.mv()\n",
    "torch.mm()\n",
    "# 范数\n",
    "torch.norm()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 累加求和\n",
    "a.cumsum(dim=1)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
